import { useState, useCallback } from 'react';
import type { CreateFlowInput } from '@/app/api/flows/route';
import { useUpload } from './useUpload';
import { clientFetch } from '@/utils/request';

interface FlowState {
  isCreating: boolean;
  isAnalyzing: boolean;
  error: string | null;
}

export function useFlow() {
  const { upload, isUploading, error: uploadError } = useUpload();

  const [state, setState] = useState<FlowState>({
    isCreating: false,
    isAnalyzing: false,
    error: null,
  });

  // 清除错误状态
  const clearError = useCallback(() => {
    setState((prev) => ({ ...prev, error: null }));
  }, []);

  // 上传图片并进行 AI 分析
  const analyseImage = useCallback(
    async (url: string): Promise<string | undefined> => {
      setState((prev) => ({ ...prev, isAnalyzing: true, error: null }));

      try {
        // 2. AI 分析
        const aiRes = await clientFetch.post<{ text: string }>(
          '/api/flows/ai',
          {
            url,
          }
        );

        if (aiRes.code !== 200) {
          throw new Error(aiRes.message || 'AI 分析失败');
        }

        return aiRes.data?.text;
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : '未知错误';
        setState((prev) => ({ ...prev, error: errorMessage }));
        throw error;
      } finally {
        setState((prev) => ({ ...prev, isAnalyzing: false }));
      }
    },
    []
  );

  // 创建流程
  const createFlow = useCallback(async (input: CreateFlowInput) => {
    setState((prev) => ({ ...prev, isCreating: true, error: null }));

    try {
      const res = await clientFetch.post('/api/flows', input);

      if (res.code !== 201) {
        throw new Error(res.message || '创建流程失败');
      }

      return res.data;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      setState((prev) => ({ ...prev, error: errorMessage }));
      throw error;
    } finally {
      setState((prev) => ({ ...prev, isCreating: false }));
    }
  }, []);

  return {
    // 方法
    analyseImage,
    createFlow,
    clearError,

    // 状态
    isUploading,
    isAnalyzing: state.isAnalyzing,
    isCreating: state.isCreating,
    isLoading: isUploading || state.isAnalyzing || state.isCreating,

    // 错误处理
    error: uploadError || state.error,
  };
}
